package com.dongpl.module.sysUser.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dongpl.annotation.MyLog;
import com.dongpl.module.sysUser.entity.SysUser;
import com.dongpl.module.sysUser.service.SysUserService;
import com.dongpl.module.sysUser.vo.RegisterUser;
import com.dongpl.utils.ShiroUtils;
import com.dongpl.utils.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 用户管理接口层
 * @author Administrator
 */
@Controller
@RequestMapping("/user")
public class SysUserController {

    @Resource
    private SysUserService userService;

    /**
     * 注册账户
     */
    @RequestMapping("/register")
    public String registerUser(@Valid RegisterUser user){
        try {
            String username = user.getUsername();
            String password = user.getPassword();
            String pass = user.getPass();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(pass)){
                return "redirect:/register";
            }
            if (!pass.equals(user.getPassword())){
                return "redirect:/register";
            }
            Boolean aBoolean = userService.registerUser(user);
            if (!aBoolean){
                return "redirect:/login";
            } else {
                return "redirect:/register";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register";
        }
    }

    /**
     * 登录用户
     */
    @RequestMapping("/login")
    public String login(String username, String password, String code, HttpSession session) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return "redirect:/login";
        }
        // 比较验证码
        String codes = (String) session.getAttribute("code");
        try {
            if (codes.equalsIgnoreCase(code)){
                //获取主体对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/admin/index";
            }else{
                throw new RuntimeException("验证码错误!");
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "redirect:/login";
    }

    /**
     * 退出账户
     */
    @RequestMapping("logout")
    public String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    /**
     * 获取验证码
     */
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        // 生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 验证码放入session
        session.setAttribute("code",code);
        // 验证码存入图片
        ServletOutputStream os = response.getOutputStream();
        // 刷新输出流
        os.flush();
        response.setContentType("image/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }

    /* *************************************** 系统内用户相关操作 ******************************************* */

    @MyLog("获取用户列表")
    @RequestMapping("getUserList")
    @ResponseBody
    public ModelAndView getUserList(){
        List<SysUser> userList = userService.getUserList();
        ModelAndView mav = new ModelAndView("admin/sys_user");
        mav.addObject("userList", userList);
        return mav;
    }

}
